package com.commerce.product.controller;

import com.commerce.common.entity.FlashSale;
import com.commerce.common.entity.FlashSaleProduct;
import com.commerce.common.utils.Result;
import com.commerce.product.service.AntiSpamService;
import com.commerce.product.service.FlashSaleService;
import com.commerce.product.service.FlashSaleStockService;
import com.commerce.product.service.impl.FlashSaleServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 秒杀活动控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/flash-sale/user")
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
public class FlashSaleController {

    @Autowired
    private FlashSaleService flashSaleService;

    @Autowired
    private FlashSaleStockService flashSaleStockService;

    @Autowired
    private AntiSpamService antiSpamService;

    /**
     * 获取当前进行中的秒杀活动
     */
    @GetMapping("/current")
    public Result<FlashSale> getCurrentFlashSale() {
        FlashSale flashSale = flashSaleService.getCurrentFlashSale();
        return Result.success(flashSale);
    }

    /**
     * 获取所有秒杀时间段
     */
    @GetMapping("/periods")
    public Result<List<FlashSale>> getAllPeriods() {
        List<FlashSale> periods = flashSaleService.getAllPeriods();
        return Result.success(periods);
    }

    /**
     * 获取秒杀活动商品列表
     */
    @GetMapping("/products/{flashSaleId}")
    public Result<List<FlashSaleProduct>> getFlashSaleProducts(@PathVariable Long flashSaleId) {
        List<FlashSaleProduct> products = flashSaleService.getFlashSaleProducts(flashSaleId);

        // 计算每个商品的售出百分比并添加实时库存信息
        products.forEach(product -> {
            // 获取Redis中的实时库存
            Integer redisStock = flashSaleStockService.getRedisStock(flashSaleId, product.getProductId());
            if (redisStock != null) {
                product.setStock(redisStock);
            }

            int total = product.getStock() + product.getSoldCount();
            int soldPercent = total > 0 ? (int) ((product.getSoldCount() * 100.0) / total) : 0;

            // 计算折扣百分比
            if (product.getOriginalPrice() != null && product.getFlashPrice() != null) {
                BigDecimal discount = product.getOriginalPrice().subtract(product.getFlashPrice())
                        .divide(product.getOriginalPrice(), 2, BigDecimal.ROUND_HALF_UP)
                        .multiply(BigDecimal.valueOf(100));
                product.setDiscountPercent(discount);
            }
        });

        return Result.success(products);
    }

    /**
     * 参与秒杀
     */
    @PostMapping("/purchase")
    public Result<String> purchaseProduct(@RequestBody Map<String, Object> params,
                                                   HttpServletRequest request) {
        try {
            // 参数校验
            if (!params.containsKey("flashSaleId") || !params.containsKey("productId") ||
                !params.containsKey("quantity")) {
                return Result.error("参数不完整");
            }

            Long flashSaleId = Long.parseLong(params.get("flashSaleId").toString());
            Long productId = Long.parseLong(params.get("productId").toString());
            Integer quantity = Integer.parseInt(params.get("quantity").toString());

            // 从请求属性中获取用户信息（由拦截器设置）
            Long userId = (Long) request.getAttribute("userId");
            String userIp = (String) request.getAttribute("userIp");
            String userAgent = (String) request.getAttribute("userAgent");

            if (userId == null) {
                return Result.error("用户未登录");
            }

            log.info("收到秒杀请求: userId={}, flashSaleId={}, productId={}, quantity={}, ip={}",
                    userId, flashSaleId, productId, quantity, userIp);

            // 调用秒杀服务
            FlashSaleServiceImpl flashSaleServiceImpl = (FlashSaleServiceImpl) flashSaleService;
            boolean success = flashSaleServiceImpl.purchaseFlashSaleProductWithUserInfo(
                flashSaleId, productId, userId, quantity, userIp, userAgent);

            if (success) {
                return Result.success("秒杀请求提交成功，请等待处理结果");
            } else {
                return Result.error("秒杀失败，商品可能已售罄或库存不足");
            }

        } catch (NumberFormatException e) {
            return Result.error("参数格式错误");
        } catch (Exception e) {
            log.error("秒杀请求处理异常: {}", e.getMessage(), e);
            return Result.error("系统繁忙，请稍后再试");
        }
    }

    /**
     * 添加秒杀活动（管理员）
     */
    @PostMapping("/admin/add")
    public Result<Boolean> addFlashSale(@RequestBody FlashSale flashSale) {
        boolean success = flashSaleService.addFlashSale(flashSale);
        return Result.success(success);
    }

    /**
     * 添加秒杀商品（管理员）
     */
    @PostMapping("/admin/product/add")
    public Result<Boolean> addFlashSaleProduct(@RequestBody Map<String, Object> params) {
        Long flashSaleId = Long.parseLong(params.get("flashSaleId").toString());
        FlashSaleProduct product = new FlashSaleProduct();

        // 设置商品属性
        product.setProductName(params.get("productName").toString());
        product.setMainImage(params.get("mainImage") != null ? params.get("mainImage").toString() : null);
        product.setOriginalPrice(new BigDecimal(params.get("originalPrice").toString()));
        product.setFlashPrice(new BigDecimal(params.get("flashPrice").toString()));
        product.setDiscountPercent(new BigDecimal(params.get("discountPercent").toString()));
        product.setStock(Integer.parseInt(params.get("stock").toString()));
        product.setSoldCount(Integer.parseInt(params.get("soldCount").toString()));
        product.setLimitPerUser(Integer.parseInt(params.get("limitPerUser").toString()));
        product.setStatus(Integer.parseInt(params.get("status").toString()));

        // 自动生成商品ID（使用当前时间戳作为唯一ID）
        product.setProductId(System.currentTimeMillis());

        boolean success = flashSaleService.addFlashSaleProduct(flashSaleId, product);
        return Result.success(success);
    }

    /**
     * 更新秒杀商品（管理员）
     */
    @PutMapping("/admin/product/update")
    public Result<Boolean> updateFlashSaleProduct(@RequestBody Map<String, Object> params) {
        try {
            Long id = Long.parseLong(params.get("id").toString());
            Long flashSaleId = Long.parseLong(params.get("flashSaleId").toString());
            Integer status = Integer.parseInt(params.get("status").toString());

            boolean success = flashSaleService.updateFlashSaleProduct(id, flashSaleId, status, params);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error("更新秒杀商品失败：" + e.getMessage());
        }
    }

    /**
     * 删除秒杀商品（管理员）
     */
    @DeleteMapping("/admin/product/delete/{id}")
    public Result<Boolean> deleteFlashSaleProduct(@PathVariable Long id) {
        boolean success = flashSaleService.deleteFlashSaleProduct(id);
        return Result.success(success);
    }

    /**
     * 更新秒杀活动（管理员）
     */
    @PutMapping("/admin/update")
    public Result<Boolean> updateFlashSale(@RequestBody FlashSale flashSale) {
        boolean success = flashSaleService.updateFlashSale(flashSale);
        return Result.success(success);
    }

    /**
     * 删除秒杀活动（管理员）
     */
    @DeleteMapping("/admin/activity/delete/{id}")
    public Result<Boolean> deleteFlashSale(@PathVariable Long id) {
        boolean success = flashSaleService.deleteFlashSale(id);
        return Result.success(success);
    }

    /**
     * 获取商品实时库存
     */
    @GetMapping("/stock/{flashSaleId}/{productId}")
    public Result<Map<String, Object>> getProductStock(@PathVariable Long flashSaleId,
                                                      @PathVariable Long productId) {
        Integer stock = flashSaleStockService.getRedisStock(flashSaleId, productId);

        Map<String, Object> result = new HashMap<>();
        result.put("flashSaleId", flashSaleId);
        result.put("productId", productId);
        result.put("stock", stock != null ? stock : 0);
        result.put("available", stock != null && stock > 0);

        return Result.success(result);
    }

    /**
     * 检查用户是否可以参与秒杀
     */
    @GetMapping("/check/{flashSaleId}/{productId}")
    public Result<Map<String, Object>> checkUserEligibility(@PathVariable Long flashSaleId,
                                                           @PathVariable Long productId,
                                                           HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        String userIp = (String) request.getAttribute("userIp");
        String userAgent = (String) request.getAttribute("userAgent");

        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 执行防刷检查
        AntiSpamService.AntiSpamResult antiSpamResult = antiSpamService.comprehensiveCheck(userId, userIp, userAgent);

        Map<String, Object> result = new HashMap<>();
        result.put("eligible", antiSpamResult.isAllowed());
        result.put("reason", antiSpamResult.getReason());

        if (antiSpamResult.isAllowed()) {
            // 检查库存
            Integer stock = flashSaleStockService.getRedisStock(flashSaleId, productId);
            result.put("stockAvailable", stock != null && stock > 0);
            result.put("currentStock", stock != null ? stock : 0);
        }

        return Result.success(result);
    }

    /**
     * 预热秒杀活动库存（管理员）
     */
    @PostMapping("/admin/preload/{flashSaleId}")
    public Result<String> preloadStock(@PathVariable Long flashSaleId) {
        try {
            flashSaleStockService.preloadFlashSaleStock(flashSaleId);
            return Result.success("库存预热成功");
        } catch (Exception e) {
            log.error("库存预热失败: flashSaleId={}, error={}", flashSaleId, e.getMessage());
            return Result.error("库存预热失败: " + e.getMessage());
        }
    }

    /**
     * 清除秒杀活动缓存（管理员）
     */
    @DeleteMapping("/admin/cache/{flashSaleId}")
    public Result<String> clearCache(@PathVariable Long flashSaleId) {
        try {
            flashSaleStockService.clearStockCache(flashSaleId);
            return Result.success("缓存清除成功");
        } catch (Exception e) {
            log.error("缓存清除失败: flashSaleId={}, error={}", flashSaleId, e.getMessage());
            return Result.error("缓存清除失败: " + e.getMessage());
        }
    }
}